// pages/myChat/myChat.js
let app=getApp();
let API=require('../../api.js').API;
let util=require('../../utils/util');
let req=require('../../utils/request').Request;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    buttons:[{
      type: 'warn',
      text:'删除'
    }]
  },
  /**
   * 监听删除聊天
   * @param {*} options 
   */
  deleteButton:function(event){
    let that=this;
    let id=event.currentTarget.dataset.id;
    let chatPeople=app.globalData.chatPeople;

    req.delete(API.deleteChatRecord+'?token='+app.globalData.token+'&destinationId='+id)
    .then(function(res){
      console.log(res);
      if(res.code==0){
        chatPeople.forEach(function(item,index){
          if(item.id==id){
            console.log(index);
            chatPeople.splice(index,1);
            that.data.users.splice(index,1);
          }
        });
        that.setData({users:that.data.users});
        
        //console.log(app.globalData.chatPeople);
      }
    }).catch(function(res){
      console.log(res);
    });
  },
  /**
   * 进入聊天界面
   * @param {*} options 
   */
  enterChat:function(event){
    let id=event.currentTarget.dataset.id;
    let online=false;
    app.globalData.chatPeople.forEach(function(item){
      if(item.id==id){
        online=item.online;
      }
    });

    wx.navigateTo({
      url:'/pages/myChat/chatWindow/chatWindow',
      success:(res)=>{
        //给后端已读未读信息的请求

        //console.log(res);
        res.eventChannel.emit('sendDestinationId',{destinationUser:{
          id:id,
          name:event.currentTarget.dataset.name,
          online:online
        }});
      }
    });
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let height = util.windowHeight(63);
    this.setData({
      scrollHeight: height
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取users信息
    let that=this;
    let userId=[];
    app.globalData.chatPeople.forEach(function(item){
      userId.push(item.id);
    });
    req.postJson(API.getUser+'?token='+app.globalData.token,userId)
    .then(function(res){
      //console.log(res);
      if(res.code==0){
        let users=res.dataMap.users;
        app.globalData.chatPeople.forEach(function(item,index){
          users[index].offlineMessage=item.offlineMessage;
          users[index].online=item.online;
        })
        //console.log(users);
        that.setData({users:users});
      }
    }).catch(function(res){
      console.log(res);
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    wx.setStorageSync('chatPeople', app.globalData.chatPeople);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})